package org.ihelpuoo.xml;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.ihelpuoo.io.StringBufferOutputStream;
import org.w3c.dom.Document;

public class XMLIO
{

	public static void printDocument(Document doc, boolean formatted) throws IOException
	{
		printDocument(doc,System.out,formatted);
	}

	public static StringBuffer toStringBuffer(Document doc)
	{
		return toStringBuffer(doc,false);
	}

	public static StringBuffer toStringBuffer(Document doc, boolean formatted)
	{
		StringBuffer sb = new StringBuffer();
		try
		{
			OutputStream ops = new StringBufferOutputStream(sb);
			printDocument(doc,ops,formatted);
			ops.close();
		}
		catch (IOException e)
		{
			throw new RuntimeException(e);
		}
		return sb;
	}

	public static void printDocument(Document doc, OutputStream ops, boolean formatted)
			throws IOException
	{
		printDocument(doc,new OutputStreamWriter(ops),formatted);
	}

	public static void printDocument(Document doc, Writer writer, boolean formatted)
			throws IOException
	{
		XMLWriter w = XMLWriter.wrap(writer);
		w.setAutoFormat(formatted);
		w.write(doc);
		w.flush();
	}

}
